package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

import model.ListSentSMS;
import model.SMS;

public class SentSMS {
	Connection connection;
	public static SentSMS isntanceSms;

	public static SentSMS getIsntance() {
		if (isntanceSms == null) {
			isntanceSms = new SentSMS();
		}
		return isntanceSms;
	}
	
	public boolean add(ListSentSMS sms) throws SQLException {
		boolean result = false;
		connection = DB_Connection.getIsntance().getConnection();
		PreparedStatement sqli = null;
		String sql = "INSERT INTO list_sent_sms(smsid, pid) VALUES ( ? , ? )";
		sqli = connection.prepareStatement(sql);
		sqli.setInt(1, sms.getSmsid());
		sqli.setInt(2, sms.getPid());
		int n = sqli.executeUpdate();
		if (n > 0)
			result = true;
		sqli.close();
		connection.close();
		return result;
	}
	public boolean add(int smsid, int pid) throws SQLException {
		boolean result = false;
		connection = DB_Connection.getIsntance().getConnection();
		PreparedStatement sqli = null;
		String sql = "INSERT INTO list_sent_sms(smsid, pid) VALUES ( ? , ? )";
		sqli = connection.prepareStatement(sql);
		sqli.setInt(1, smsid);
		sqli.setInt(2, pid);
		int n = sqli.executeUpdate();
		if (n > 0)
			result = true;
		sqli.close();
		connection.close();
		return result;
	}
	public boolean sen(SMS sms, int[] pid){
		boolean result =true;
		int smsid = 0;
		if(!SMSMod.getIsntance().isSMSid(sms.getSmsid())){
			if(SMSMod.getIsntance().add(sms)){
				smsid = SMSMod.getIsntance().getSMS(sms).getSmsid();
			}else{
				result = false;
			}
		}else{
			smsid = sms.getSmsid();
		}
		for (int i: pid) {
			try {
				SentSMS.getIsntance().add(smsid, i);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
		
	}
	public ArrayList<ListSentSMS> getListSent(int smsid){
		ArrayList<ListSentSMS>  result = null;
		connection = DB_Connection.getIsntance().getConnection();
		try {
			String sql = "SELECT * FROM list_sent_sms WHERE smsid = ? ";
			PreparedStatement sqli = connection.prepareStatement(sql);
			sqli.setInt(1, smsid);
			ResultSet rs = sqli.executeQuery();
			while(rs.next()){
				result.add(new ListSentSMS(rs.getInt(1), rs.getInt(2), rs.getInt(3)));
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		return result;
	}
}
